package libs;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import play.Application;
import play.GlobalSettings;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Http.Request;
import play.mvc.SimpleResult;

public class Global extends GlobalSettings {

    public static EntityManager entityManager;

    public void onStart(Application app) {
            // Get the EntityManager Factory
            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
            // Get the Entity Manager
            if(entityManager == null)
                    entityManager = entityManagerFactory.createEntityManager();
    }

    public void onStop(Application app) {
            entityManager.clear();
            entityManager.close();
            entityManager = null;
    }
    
    @SuppressWarnings({ "rawtypes" })
    @Override
    public Action onRequest(Request request, Method actionMethod) {
            List<String> arrPath = Arrays.asList("Application/login", "Application/signup");
            String actionPath = actionMethod.getDeclaringClass().getSimpleName() + "/" + actionMethod.getName();
            System.out.println("The path of controller ..." + actionPath);

            if (!arrPath.contains(actionPath)) {
                    return new Action.Simple() {
                            @Override
                            public Promise<SimpleResult> call(Context ctx) throws Throwable {
                                    System.out.println(ctx.session().get("userId"));
                                    if (Validation.isEmpty(ctx.session().get("userId"))) {
                                            System.out.println("redirect to login!!!");
                                            return Promise.pure(redirect("/login"));
                                    }
                                    return delegate.call(ctx);
                            }
                    };
            }
            return super.onRequest(request, actionMethod);
    }

}
